package com.org.gundutubruk;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.util.Log;

public class Utility {
	
	public static PlayerHolder playerHolder = new PlayerHolder();
	public static final String TAG = Utility.class.getSimpleName();
	
	public static boolean checkPlayerHolderAlreadyExist(Context context) {
		String[] arrfiles = context.fileList();
		for(String s : arrfiles) {
			if(s.equals("playerholder.ser")) {
				return true;
			}
		}
		return false;
	}
	
	public static void serializePlayerHolder(Context context) {
		String filename = "playerholder.ser";			
		FileOutputStream fos = null;
		ObjectOutputStream out = null;		
		try {
			fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
			out = new ObjectOutputStream(fos);
			out.writeObject(playerHolder);
			out.close();
		}catch(IOException e) {		
			Log.d(TAG, "error IO saat serialisasi");
		}
	}
	
	public static void deserializePlayerHolder(Context context) {
		String filename = "playerholder.ser";
		playerHolder = null;
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try{
			fis = context.openFileInput(filename);
			in = new ObjectInputStream(fis);
			playerHolder = (PlayerHolder) in.readObject();			
			in.close();						
		}catch(IOException e) {
			Log.d(TAG, "error IO saat DEserialisasi");			
			playerHolder = new PlayerHolder();
		} catch (ClassNotFoundException e) {
			Log.d(TAG, "error ClassNotFound saat serialisasi");
		}
	}
	
	public static double getArea(Coordinate a, Coordinate b, Coordinate c) {
		return Math.abs(a.x*b.y+b.x*c.y+c.x*a.y-a.x*c.y-c.x*b.y-b.x*a.y)/2; 
	}
	
	public static boolean checkPointInsideTriangle(Coordinate a, Coordinate b, Coordinate c, Coordinate p) {
		double epsilon = 0.1;
		double area = getArea(a,b,c);
		double PAB = getArea(p,a,b);
		double PBC = getArea(p,b,c);
		double PCA = getArea(p,c,a);
		return Math.abs(area - (PAB+PBC+PCA)) < epsilon;
	}
	
	
}
